package com.wanpinghui.supplier.message.nim;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.media.RingtoneManager;
import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.Observer;
import com.netease.nimlib.sdk.RequestCallback;
import com.netease.nimlib.sdk.SDKOptions;
import com.netease.nimlib.sdk.StatusBarNotificationConfig;
import com.netease.nimlib.sdk.StatusCode;
import com.netease.nimlib.sdk.auth.AuthService;
import com.netease.nimlib.sdk.auth.AuthServiceObserver;
import com.netease.nimlib.sdk.auth.LoginInfo;
import com.netease.nimlib.sdk.msg.MessageBuilder;
import com.netease.nimlib.sdk.msg.MsgService;
import com.netease.nimlib.sdk.msg.MsgServiceObserve;
import com.netease.nimlib.sdk.msg.SystemMessageObserver;
import com.netease.nimlib.sdk.msg.constant.SessionTypeEnum;
import com.netease.nimlib.sdk.msg.model.CustomNotification;
import com.netease.nimlib.sdk.msg.model.IMMessage;
import com.netease.nimlib.sdk.msg.model.SystemMessage;
import com.netease.nimlib.sdk.uinfo.UserInfoProvider;
import com.netease.nimlib.sdk.uinfo.UserService;
import com.netease.nimlib.sdk.uinfo.model.NimUserInfo;
import com.wanpinghui.supplier.MApplication;
import com.wanpinghui.supplier.R;
import com.wanpinghui.supplier.object.HomePageActivity;
import com.wanpinghui.wphlibrary.WPHSdk;
import com.wanpinghui.wphlibrary.model.db.manager.MsgDbManager;
import com.wanpinghui.wphlibrary.model.message.MessageService;
import com.wanpinghui.wphlibrary.model.message.bean.CustomerNotificationContent;
import com.wanpinghui.wphlibrary.model.message.bean.MessagesExt;
import com.wanpinghui.wphlibrary.model.message.bean.MsgBean;
import com.wanpinghui.wphlibrary.model.message.bean.MsgFileBean;
import com.wanpinghui.wphlibrary.model.message.bean.RecentMsgBean;
import com.wanpinghui.wphlibrary.model.oauth.OAuthService;
import com.wanpinghui.wphlibrary.model.oauth.bean.UserBean;
import com.wanpinghui.wphlibrary.model.oauth.bean.UserInformation;
import com.yunshl.yunshllibrary.storage.StorageManager;
import com.yunshl.yunshllibrary.utils.DevicesUtil;
import com.yunshl.yunshllibrary.utils.LogUtils;
import com.yunshl.yunshllibrary.utils.SystemUtil;
import com.yunshl.yunshllibrary.utils.TextUtil;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import retrofit.callback.YRequestCallback;

/***
 * 功能描述: nim message
 * 作者:xiongning
 * 时间:2017/11/23
 ***/

public class NimManager {

    private static NimManager instance;

    private Observer<StatusCode> mStatuObserver;

    private Observer<List<IMMessage>> incomingMessageObserver;

    private INIMListener mINIMListener;

    private String chatIM = null;

    private INIMRcvMsgListener mINIMRcvMsgListener;

    private List<INimNotificationListener> notificationListeners;

    private List<String> list;

    private Observer<CustomNotification> notificationObserver;

    public interface INIMListener {

        void onConnecting();

        void onConnected();

        void onWaringTip(String msg, boolean reqLogin);

    }

    public interface INIMRcvMsgListener {

        void onMsgRcv(List<MsgBean> datas);

        void onRecentMsgRcv(List<RecentMsgBean> datas);
    }

    public interface INNIMSendMsgListener {
        void onSendMsg(MsgBean msgBean);//0:sending 1:success 2 failed
    }

    public interface INimNotificationListener{
        void onReceiveNotification(long messageTime, CustomerNotificationContent content);
    }

    private NimManager() {
        list = new ArrayList<>();
    }

    public void initAccount(List<RecentMsgBean> datas, RequestCallback callback) {

        if (datas != null && datas.size() > 0) {

            List<String> accounts = new ArrayList<>();

            for (RecentMsgBean rmb : datas) {
                accounts.add(rmb.getChatImId());
            }

            NIMClient.getService(UserService.class).fetchUserInfo(accounts).setCallback(callback);
        }
    }

    public NimUserInfo getUser(String account, RequestCallback callback) {
        NimUserInfo user = NIMClient.getService(UserService.class).getUserInfo(account);
        if (user == null) {
            List<String> accounts = new ArrayList<>();
            accounts.add(account);
            NIMClient.getService(UserService.class).fetchUserInfo(accounts).setCallback(callback);
        }else if (list== null || !list.contains(account)){
            List<String> accounts = new ArrayList<>();
            accounts.add(account);
            NIMClient.getService(UserService.class).fetchUserInfo(accounts).setCallback(null);
            list.add(account);
        }
        return user;
    }

    public static NimManager getInstance() {
        if (instance == null) {
            instance = new NimManager();
        }
        return instance;
    }

    public void init(Context mContext) {

        int thumbnailSize = DevicesUtil.getWidth(mContext) / 2;
        // SDK初始化（启动后台服务，若已经存在用户登录信息， SDK 将完成自动登录）
        LoginInfo loginInfo = loginInfo();
        NIMClient.init(mContext, loginInfo, options(thumbnailSize));
        //NIMClient.getService(MsgService.class).registerCustomAttachmentParser(new WPHAttachParser());

        initObserver();
    }

    //INVALID	未定义
    //UNLOGIN	未登录/登录失败
    //NET_BROKEN	网络连接已断开
    //CONNECTING	正在连接服务器
    //LOGINING	正在登录中
    //SYNCING	正在同步数据
    //LOGINED	已成功登录
    //KICKOUT	被其他端的登录踢掉
    //KICK_BY_OTHER_CLIENT	被同时在线的其他端主动踢掉
    //FORBIDDEN	被服务器禁止登录
    //VER_ERROR	客户端版本错误
    //PWD_ERROR	用户名或密码错误
    private void initObserver() {
        mStatuObserver = new Observer<StatusCode>() {
            @Override
            public void onEvent(StatusCode statusCode) {
                switch (statusCode) {
                    case INVALID:
                        if (mINIMListener != null)
                            mINIMListener.onWaringTip("未定义", false);
                        break;
                    case UNLOGIN:
                        if (mINIMListener != null)
                            mINIMListener.onWaringTip("未登录/登录失败", true);
                        break;
                    case NET_BROKEN:
                        if (mINIMListener != null)
                            mINIMListener.onWaringTip("网络连接已断开", false);
                        break;
                    case CONNECTING:
                    case SYNCING:
                    case LOGINING:
                        if (mINIMListener != null)
                            mINIMListener.onConnecting();
                        break;
                    case LOGINED:
                        if (mINIMListener != null)
                            mINIMListener.onConnected();
                        break;
                    case KICKOUT:
                        if (mINIMListener != null)
                            mINIMListener.onWaringTip("被其他端的登录踢掉", true);
                        break;
                    case KICK_BY_OTHER_CLIENT:
                        if (mINIMListener != null)
                            mINIMListener.onWaringTip("被同时在线的其他端主动踢掉", true);
                        break;
                    case FORBIDDEN:
                        if (mINIMListener != null)
                            mINIMListener.onWaringTip("被服务器禁止登录", false);
                        break;
                    case VER_ERROR:
                        if (mINIMListener != null)
                            mINIMListener.onWaringTip("客户端版本错误", false);
                        break;
                    case PWD_ERROR:
                        if (mINIMListener != null)
                            mINIMListener.onWaringTip("用户名或密码错误", true);
                        break;
                }

            }
        };
    }

    public void enterChat(String chatIM) {

        NIMClient.getService(MsgService.class).setChattingAccount(chatIM, SessionTypeEnum.P2P);

    }

    public void enterRecentChat() {

        NIMClient.getService(MsgService.class).setChattingAccount(MsgService.MSG_CHATTING_ACCOUNT_ALL, SessionTypeEnum.None);
    }

    public void quitChat() {
        NIMClient.getService(MsgService.class).setChattingAccount(MsgService.MSG_CHATTING_ACCOUNT_NONE, SessionTypeEnum.None);
    }

    public void addNotificationListener(INimNotificationListener listener) {
        if (notificationListeners == null) {
            notificationListeners = new ArrayList<>();
            notificationObserver = new Observer<CustomNotification>() {
                @Override
                public void onEvent(CustomNotification customNotification) {
                    if (customNotification != null) {
                        String content = customNotification.getContent();
                        LogUtils.d("NimManager","CustomNotification-----"+content);
                        if (TextUtil.isNotEmpty(content)) {
                            try {
                                CustomerNotificationContent content1 = new Gson().fromJson(content,new TypeToken<CustomerNotificationContent>(){}.getType());
                                if (content1 != null && content1.getType() == 0) {
                                    if (notificationListeners != null && notificationListeners.size() > 0) {
                                        for (INimNotificationListener listener1 : notificationListeners) {
                                            listener1.onReceiveNotification(customNotification.getTime(), content1);
                                        }
                                    }
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }
            };
            NIMClient.getService(MsgServiceObserve.class).observeCustomNotification(notificationObserver,true);
        }
        notificationListeners.add(listener);
    }

    public void removeNotificationListener(INimNotificationListener listener) {
        if (notificationListeners != null && notificationListeners.size() > 0) {
            notificationListeners.remove(listener);
        }
        if (notificationListeners.size() == 0) {
            notificationListeners = null;
            if (notificationObserver != null) {
                NIMClient.getService(MsgServiceObserve.class).observeCustomNotification(notificationObserver,false);
            }
        }
    }

    public void initIncommingRcvObserver() {

        if (incomingMessageObserver == null) {
            NIMClient.getService(MsgService.class).registerCustomAttachmentParser(new WPHAttachParser());
            incomingMessageObserver = new Observer<List<IMMessage>>() {
                @Override
                public void onEvent(List<IMMessage> messages) {
                    // 处理新收到的消息，为了上传处理方便，SDK 保证参数 messages 全部来自同一个聊天对象
                    saveMsgBeans(messages);

                }
            };

            regMsgRcvListener(true);

            if (SystemUtil.isNotificationEnabled(MApplication.getAContext())) {
                enableNotification(true);
            } else {
                enableNotification(false);
            }
        }

    }

    public void enableNotification(boolean isEnable) {

        NIMClient.toggleNotification(isEnable);
    }

    private MsgBean getMsbBean(IMMessage mIMMessage, String chatIM) {
        Object object = mIMMessage.getAttachment();
        if (object != null) {
            WPHMsg wphmsg = (WPHMsg) object;
            String account = mIMMessage.getFromAccount();
            if (TextUtil.isNotEmpty(chatIM))
                account = chatIM;
            int direct = mIMMessage.getDirect().getValue();
            long time = mIMMessage.getTime();
            int msg_type = wphmsg.getMsg_type();
            int type = wphmsg.getType();
            String msg = wphmsg.getMsg();
            String ext = wphmsg.getExt();
            return new MsgBean(account, msg, ext, type, msg_type, time, direct);
        }
        return null;
    }

    private List<MsgBean> saveMsgBeans(List<IMMessage> messages) {
        List<MsgBean> datas = null;
        String account = null;
        if (messages != null && messages.size() > 0) {
            datas = new ArrayList<>();
            for (IMMessage msg : messages) {
                account = msg.getFromAccount();
                MsgBean mb = getMsbBean(msg, null);
                if (mb != null)
                    datas.add(mb);
            }
            if (datas != null && datas.size() > 0) {
                MsgDbManager.getInstance().saveMsbBeanList(datas);
                MsgDbManager.getInstance().saveRecentMsgBeanList(datas, TextUtil.isNotEmpty(chatIM));
                List<RecentMsgBean> rmbs = WPHSdk.getService(MessageService.class).setRecentMsgBeanCache(datas, TextUtil.isNotEmpty(chatIM));
                if (mINIMRcvMsgListener != null) {
                    MsgBean mb = datas.get(0);
                    if (mb != null && TextUtil.isNotEmpty(chatIM) && TextUtil.equals(chatIM, account)) {
                        mINIMRcvMsgListener.onMsgRcv(datas);
                    }
                    mINIMRcvMsgListener.onRecentMsgRcv(rmbs);
                }
            }
        }
        return datas;
    }

    private void notifyRecentMsgSend(MsgBean mb) {
        getUser(mb.getAccount(), null);
        MsgDbManager.getInstance().saveRecentMsgBean(mb, TextUtil.isNotEmpty(chatIM));
        List<RecentMsgBean> rmbs = WPHSdk.getService(MessageService.class).setRecentMsgBeanCache(mb, TextUtil.isNotEmpty(chatIM));
        if (mINIMRcvMsgListener != null) {
            mINIMRcvMsgListener.onRecentMsgRcv(rmbs);
        }
    }

    public void registerRcvListener(String chatIM, INIMRcvMsgListener mINIMRcvMsgListener) {
        this.chatIM = chatIM;
        this.mINIMRcvMsgListener = mINIMRcvMsgListener;
    }

    // 如果返回值为 null，则全部使用默认参数。
    private SDKOptions options(int thumbnailSize) {
        SDKOptions options = new SDKOptions();
        // 如果将新消息通知提醒托管给 SDK 完成，需要添加以下配置。否则无需设置。
        StatusBarNotificationConfig config = new StatusBarNotificationConfig();
        config.notificationEntrance = HomePageActivity.class; // 点击通知栏跳转到该Activity
        //config.notificationSmallIconId = R.drawable.ic_stat_notify_msg;
        // 呼吸灯配置
        config.ledARGB = Color.GREEN;
        config.ledOnMs = 1000;
        config.ledOffMs = 1500;
        // 通知铃声的uri字符串
        config.notificationSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION) + "";//"android.resource://com.netease.nim.demo/raw/msg";
        options.statusBarNotificationConfig = config;
        // 配置保存图片，文件，log 等数据的目录
        // 如果 options 中没有设置这个值，SDK 会使用采用默认路径作为 SDK 的数据目录。
        // 该目录目前包含 log, file, image, audio, video, thumb 这6个目录。
        //String sdkPath = getAppCacheDir(context) + "/nim"; // 可以不设置，那么将采用默认路径
        // 如果第三方 APP 需要缓存清理功能， 清理这个目录下面个子目录的内容即可。
        options.sdkStorageRootPath = StorageManager.getNimPath();
        // 配置是否需要预下载附件缩略图，默认为 true
        options.preloadAttach = true;
        // 配置附件缩略图的尺寸大小。表示向服务器请求缩略图文件的大小
        // 该值一般应根据屏幕尺寸来确定， 默认值为 Screen.width / 2
        options.thumbnailSize = thumbnailSize;
        // 用户资料提供者, 目前主要用于提供用户资料，用于新消息通知栏中显示消息来源的头像和昵称
        options.userInfoProvider = new UserInfoProvider() {
            @Override
            public UserInfo getUserInfo(String account) {
                return null;
            }

            @Override
            public int getDefaultIconResId() {
                return R.mipmap.my_icon_head_default;
            }

            @Override
            public Bitmap getTeamIcon(String tid) {
                return null;
            }

            @Override
            public Bitmap getAvatarForMessageNotifier(String account) {
                return null;
            }

            @Override
            public String getDisplayNameForMessageNotifier(String account, String sessionId, SessionTypeEnum sessionType) {
                return null;
            }
        };
        return options;
    }

    //logout
    public void logout() {
        NIMClient.getService(AuthService.class).logout();
    }

    // 如果已经存在用户登录信息，返回LoginInfo，否则返回null即可
    private LoginInfo loginInfo() {
        LoginInfo info = null;
        UserBean userBeanInfo = WPHSdk.getService(OAuthService.class).getUserInfo(null);
        UserInformation userBean = null;
        if (userBeanInfo != null) {
            userBean = userBeanInfo.getUser();
            if (userBean != null) {
                info = new LoginInfo(userBean.getId(), userBean.getIm_token());
            }
        }
        return info;
    }

    //login
    public void login() {

        NIMClient.getService(AuthService.class).login(loginInfo()).setCallback(new RequestCallback<LoginInfo>() {
            @Override
            public void onSuccess(LoginInfo param) {
                //ToastManager.getInstance().showToast("login success");
                // Log.e("Login","llogin success");
                initIncommingRcvObserver();
            }

            @Override
            public void onFailed(int code) {
                //ToastManager.getInstance().showToast("login failed,code="+code);
                //Log.e("Login","login failed,code="+code);
            }

            @Override
            public void onException(Throwable exception) {
                //ToastManager.getInstance().showToast("login failed,exception="+exception.getMessage());
                //Log.e("Login","login failed,exception="+exception.getMessage());
            }
        });
    }

    public boolean isOnline() {

        boolean isOnline = false;

        StatusCode status = NIMClient.getStatus();

        if (status == StatusCode.LOGINED)
            isOnline = true;

        return isOnline;

    }

    public void regOrUnregOnline(INIMListener mINIMListener, boolean isReg) {
        if (isReg) {
            this.mINIMListener = mINIMListener;
        } else {
            this.mINIMListener = null;
        }
        NIMClient.getService(AuthServiceObserver.class).observeOnlineStatus(mStatuObserver, isReg);
    }

    public void regMsgRcvListener(boolean isReg) {

        NIMClient.getService(MsgServiceObserve.class).observeReceiveMessage(incomingMessageObserver, isReg);
    }

    /**
     * 3.质量压缩
     * 设置bitmap options属性，降低图片的质量，像素不会减少
     * 第一个参数为需要压缩的bitmap图片对象，第二个参数为压缩后图片保存的位置
     * 设置options 属性0-100，来实现压缩
     */
    public static String qualityCompress(String filePath) {
        // 0-100 100为不压缩
        int quality = 80;
        Bitmap bitmap = BitmapFactory.decodeFile(filePath);
        String path=StorageManager.getFileDir()+"/"+System.currentTimeMillis()+".jpeg";
        File file=new File(path);
        if(!file.exists())
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        // 把压缩后的数据存放到baos中
        bitmap.compress(Bitmap.CompressFormat.JPEG, quality, baos);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            fos.write(baos.toByteArray());
            fos.flush();
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return file.getAbsolutePath();
    }

    private void sendUploadMsg(final String chatIM, String filePath, final IMMessage message, final INNIMSendMsgListener listener) {
        Log.e("NimManager","filePath="+filePath);
        filePath=qualityCompress(filePath);
        WPHSdk.getService(MessageService.class).uploadFile(filePath, new YRequestCallback() {
            @Override
            public void onSuccess(Object var1) {
                if (var1 != null && var1 instanceof MsgFileBean) {
                    MsgFileBean mfb = (MsgFileBean) var1;
                    WPHMsg mWPHMsg = (WPHMsg) message.getAttachment();
                    mWPHMsg.setMsg(mfb.getUrl());
                    final MsgBean mb = getMsbBean(message, chatIM);
                    NIMClient.getService(MsgService.class).sendMessage(message, true).setCallback(new RequestCallback<Void>() {
                        @Override
                        public void onSuccess(Void param) {
                            mb.setSend_statu(1);
                            WPHSdk.getService(MessageService.class).saveSendMsbBean(mb, null, true);
                            if (listener != null)
                                listener.onSendMsg(mb);
                            notifyRecentMsgSend(mb);
                        }

                        @Override
                        public void onFailed(int code) {
                            mb.setSend_statu(2);
                            WPHSdk.getService(MessageService.class).saveSendMsbBean(mb, null, false);
                            if (listener != null)
                                listener.onSendMsg(mb);
                            notifyRecentMsgSend(mb);

                        }

                        @Override
                        public void onException(Throwable exception) {
                            mb.setSend_statu(2);
                            WPHSdk.getService(MessageService.class).saveSendMsbBean(mb, null, false);
                            if (listener != null)
                                listener.onSendMsg(mb);
                            notifyRecentMsgSend(mb);

                        }
                    });
                }
            }

            @Override
            public void onFailed(int var1, String messages) {
                MsgBean mb = getMsbBean(message, chatIM);
                mb.setSend_statu(2);
                WPHSdk.getService(MessageService.class).saveSendMsbBean(mb, null, false);
                if (listener != null)
                    listener.onSendMsg(mb);
                notifyRecentMsgSend(mb);
            }

            @Override
            public void onException(Throwable var1) {
                MsgBean mb = getMsbBean(message, chatIM);
                mb.setSend_statu(2);
                WPHSdk.getService(MessageService.class).saveSendMsbBean(mb, null, false);
                if (listener != null)
                    listener.onSendMsg(mb);
                notifyRecentMsgSend(mb);

            }
        });
    }

    public void sendImgMsg(String account, int msg_type, int type, String msg, MessagesExt mMessagesExt, INNIMSendMsgListener listener) {
        String tip = "[图片]";
        WPHMsg attachment = new WPHMsg(msg_type, msg, type, mMessagesExt.getExt());
        IMMessage message = MessageBuilder.createCustomMessage(account, SessionTypeEnum.P2P, tip, attachment);
        MsgBean sendingMsb = getMsbBean(message, account);
        if (listener != null)
            listener.onSendMsg(sendingMsb);
        sendUploadMsg(account, mMessagesExt.getFile_path(), message, listener);
    }

    public void sendAudioMsg(String account, int msg_type, int type, String msg, MessagesExt mMessagesExt, INNIMSendMsgListener listener) {
        String tip = "[语音]";
        WPHMsg attachment = new WPHMsg(msg_type, msg, type, mMessagesExt.getExt());
        IMMessage message = MessageBuilder.createCustomMessage(account, SessionTypeEnum.P2P, tip, attachment);
        MsgBean sendingMsb = getMsbBean(message, account);
        if (listener != null)
            listener.onSendMsg(sendingMsb);
        sendUploadMsg(account, mMessagesExt.getFile_path(), message, listener);
    }

    public void sendFileMsg(String account, int msg_type, int type, String msg, MessagesExt mMessagesExt, INNIMSendMsgListener listener) {
        String tip = "[文件]";
        WPHMsg attachment = new WPHMsg(msg_type, msg, type, mMessagesExt.getExt());
        IMMessage message = MessageBuilder.createCustomMessage(account, SessionTypeEnum.P2P, tip, attachment);
        MsgBean sendingMsb = getMsbBean(message, account);
        if (listener != null)
            listener.onSendMsg(sendingMsb);
        sendUploadMsg(account, mMessagesExt.getFile_path(), message, listener);
    }

    public void sendOrderMsg(String account, int msg_type, String orderJson, final INNIMSendMsgListener listener) {
        String tip = "[交易消息]";
        LogUtils.w("orderJson : " + orderJson);
        WPHMsg attachment = new WPHMsg(msg_type, "", WPHMsg.MSG_ORDER, orderJson);
        IMMessage message = MessageBuilder.createCustomMessage(account, SessionTypeEnum.P2P, tip, attachment);
        MsgBean sendingMsb = getMsbBean(message, account);
        if (listener != null)
            listener.onSendMsg(sendingMsb);
        final MsgBean mb = getMsbBean(message, account);
        NIMClient.getService(MsgService.class).sendMessage(message, true).setCallback(new RequestCallback<Void>() {
            @Override
            public void onSuccess(Void param) {
                mb.setSend_statu(1);
                if (listener != null)
                    listener.onSendMsg(mb);
                WPHSdk.getService(MessageService.class).saveSendMsbBean(mb, null, true);
                notifyRecentMsgSend(mb);
            }

            @Override
            public void onFailed(int code) {
                LogUtils.w("发送消息失败[" + code + "]");
                mb.setSend_statu(2);
                if (listener != null)
                    listener.onSendMsg(mb);
                WPHSdk.getService(MessageService.class).saveSendMsbBean(mb, null, false);
                notifyRecentMsgSend(mb);
            }

            @Override
            public void onException(Throwable exception) {
                mb.setSend_statu(2);
                if (listener != null)
                    listener.onSendMsg(mb);
                WPHSdk.getService(MessageService.class).saveSendMsbBean(mb, null, false);
                notifyRecentMsgSend(mb);
            }
        });
    }

    public void sendTxtMsg(String account, int msg_type, int type, String msg, final INNIMSendMsgListener listener) {
        WPHMsg attachment = new WPHMsg(msg_type, type, msg);
        IMMessage message = MessageBuilder.createCustomMessage(account, SessionTypeEnum.P2P, msg, attachment);
        MsgBean sendingMsb = getMsbBean(message, account);
        if (listener != null)
            listener.onSendMsg(sendingMsb);
        final MsgBean mb = getMsbBean(message, account);
        NIMClient.getService(MsgService.class).sendMessage(message, true).setCallback(new RequestCallback<Void>() {
            @Override
            public void onSuccess(Void param) {
                mb.setSend_statu(1);
                if (listener != null)
                    listener.onSendMsg(mb);
                WPHSdk.getService(MessageService.class).saveSendMsbBean(mb, null, true);
                notifyRecentMsgSend(mb);
            }

            @Override
            public void onFailed(int code) {
                mb.setSend_statu(2);
                if (listener != null)
                    listener.onSendMsg(mb);
                WPHSdk.getService(MessageService.class).saveSendMsbBean(mb, null, false);
                notifyRecentMsgSend(mb);
            }

            @Override
            public void onException(Throwable exception) {
                mb.setSend_statu(2);
                if (listener != null)
                    listener.onSendMsg(mb);
                WPHSdk.getService(MessageService.class).saveSendMsbBean(mb, null, false);
                notifyRecentMsgSend(mb);
            }
        });
    }
}
